package com.zhentao.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.dto.WechatUserDTO;
import com.zhentao.mapper.WechatUserMapper;
import com.zhentao.pojo.R;
import com.zhentao.pojo.WechatUser;
import com.zhentao.request.WxLoginRequest;
import com.zhentao.request.WxPhoneRequest;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("user")
public class UserController {

    private final WxMaService wxMaService;
    private final WechatUserMapper wechatUserMapper;

    public UserController(WxMaService wxMaService, WechatUserMapper wechatUserMapper) {
        this.wxMaService = wxMaService;
        this.wechatUserMapper = wechatUserMapper;
    }

    // 发送验证码接口
    @PostMapping("/send-verification-code")
    public R<String> sendVerificationCode(@RequestBody Map<String, String> request) {
        try {
            String phoneNumber = request.get("phoneNumber");
            System.out.println("发送验证码请求，手机号: " + phoneNumber);
            
            if (phoneNumber == null || phoneNumber.trim().isEmpty()) {
                return R.failed("手机号不能为空");
            }
            
            // 验证手机号格式
            if (!phoneNumber.matches("^1[3-9]\\d{9}$")) {
                return R.failed("手机号格式不正确");
            }
            
            // 开发测试阶段：生成验证码并显示在控制台
            String verificationCode = generateTestVerificationCode();
            System.out.println("=== 开发测试模式 ===");
            System.out.println("手机号: " + phoneNumber);
            System.out.println("验证码: " + verificationCode);
            System.out.println("请在前端输入此验证码进行测试");
            System.out.println("==================");
            
            // TODO: 生产环境使用真正的短信服务
            // String verificationCode = smsService.sendVerificationCode(phoneNumber);
            
            return R.ok("验证码发送成功（开发模式）");
        } catch (Exception e) {
            System.err.println("发送验证码失败: " + e.getMessage());
            System.err.println("详细错误信息: " + e.toString());
            return R.failed("发送验证码失败：" + e.getMessage());
        }
    }
    
    /**
     * 生成测试用验证码（仅开发阶段使用）
     */
    private String generateTestVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    // 验证验证码并更新手机号接口
    @PostMapping("/verify-code")
    public R<String> verifyCode(@RequestBody Map<String, String> request) {
        try {
            String phoneNumber = request.get("phoneNumber");
            String verificationCode = request.get("verificationCode");
            String openid = request.get("openid");
            
            System.out.println("验证验证码请求 - 手机号: " + phoneNumber + ", 验证码: " + verificationCode + ", openid: " + openid);
            
            if (phoneNumber == null || verificationCode == null) {
                return R.failed("手机号和验证码不能为空");
            }
            
            // 开发测试阶段：这里应该验证验证码是否正确
            // 由于我们使用的是测试模式，这里简单判断验证码长度
            if (verificationCode.length() != 6) {
                return R.failed("验证码格式不正确");
            }
            
            // 如果提供了openid，更新用户手机号
            if (openid != null && !openid.trim().isEmpty()) {
                LambdaQueryWrapper<WechatUser> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(WechatUser::getOpenid, openid);
                WechatUser user = wechatUserMapper.selectOne(wrapper);
                
                if (user != null) {
                    System.out.println("更新用户手机号，原手机号: " + user.getPhone() + ", 新手机号: " + phoneNumber);
                    user.setPhone(phoneNumber);
                    user.setUpdateTime(LocalDateTime.now());
                    int updateResult = wechatUserMapper.updateById(user);
                    System.out.println("手机号更新结果: " + updateResult);
                    
                    if (updateResult > 0) {
                        return R.ok("验证成功，手机号已更新");
                    } else {
                        return R.failed("手机号更新失败");
                    }
                } else {
                    System.out.println("未找到用户，openid: " + openid);
                    return R.failed("用户不存在");
                }
            } else {
                // 如果没有openid，只验证验证码
                return R.ok("验证码验证成功");
            }
            
        } catch (Exception e) {
            System.err.println("验证验证码失败: " + e.getMessage());
            System.err.println("详细错误信息: " + e.toString());
            return R.failed("验证验证码失败：" + e.getMessage());
        }
    }

    // 测试接口 - 查询所有用户
    @GetMapping("/test")
    public R<List<WechatUser>> testDatabase() {
        try {
            List<WechatUser> users = wechatUserMapper.selectList(null);
            System.out.println("查询到用户数量: " + users.size());
            for (WechatUser user : users) {
                System.out.println("用户信息: " + user);
            }
            return R.ok(users);
        } catch (Exception e) {
            System.err.println("测试数据库连接失败: " + e.getMessage());
            System.err.println("详细错误信息: " + e.toString());
            return R.failed("数据库连接失败: " + e.getMessage());
        }
    }

    // 刷新用户数据接口（不依赖微信登录码）
    @PostMapping("/refresh-user")
    public R<WechatUserDTO> refreshUserData(@RequestBody Map<String, String> request) {
        try {
            String openid = request.get("openid");
            System.out.println("刷新用户数据请求，openid: " + openid);
            
            if (openid == null || openid.trim().isEmpty()) {
                return R.failed("openid不能为空");
            }
            
            // 根据openid查询用户信息
            LambdaQueryWrapper<WechatUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WechatUser::getOpenid, openid);
            WechatUser user = wechatUserMapper.selectOne(wrapper);
            
            if (user == null) {
                return R.failed("用户不存在");
            }
            
            System.out.println("刷新用户数据，查询到用户: " + user);
            System.out.println("用户手机号: " + user.getPhone());
            
            // 返回最新的用户信息
            WechatUserDTO dto = new WechatUserDTO(user);
            return R.ok(dto);
            
        } catch (Exception e) {
            System.err.println("刷新用户数据失败: " + e.getMessage());
            System.err.println("详细错误信息: " + e.toString());
            return R.failed("刷新用户数据失败：" + e.getMessage());
        }
    }

    // 微信一键登录接口
    @PostMapping("/wx-login")
    public R<WechatUserDTO> wxLogin(@RequestBody WxLoginRequest request) {
        try {
            // 1. 调用微信接口获取 openid 和 unionid
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(request.getCode());
            String openid = session.getOpenid();
            String unionid = session.getUnionid();

            System.out.println("获取到openid: " + openid);
            System.out.println("获取到unionid: " + unionid);
            System.out.println("用户信息: " + request.getUserInfo());

            // 2. 查询或创建用户
            LambdaQueryWrapper<WechatUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WechatUser::getOpenid, openid);
            WechatUser user = wechatUserMapper.selectOne(wrapper);

            if (user == null) {
                // 创建新用户
                user = WechatUser.builder()
                        .openid(openid)
                        .unionid(unionid)
                        .nickname(request.getUserInfo().getNickName())
                        .avatarUrl(request.getUserInfo().getAvatarUrl())
                        .phone("") // 新用户手机号初始为空
                        .gender(request.getUserInfo().getGender())
                        .province(request.getUserInfo().getProvince())
                        .city(request.getUserInfo().getCity())
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build();
                
                System.out.println("创建新用户: " + user);
                int insertResult = wechatUserMapper.insert(user);
                System.out.println("插入结果: " + insertResult);
                
            } else {
                // 更新用户信息
                System.out.println("更新现有用户，原信息: " + user);
                
                user.setUnionid(unionid);
                user.setNickname(request.getUserInfo().getNickName());
                user.setAvatarUrl(request.getUserInfo().getAvatarUrl());
                
                // 只有当手机号不为空时才更新
                if (request.getUserInfo().getPhoneNumber() != null && !request.getUserInfo().getPhoneNumber().isEmpty()) {
                    user.setPhone(request.getUserInfo().getPhoneNumber());
                }
                // 如果前端没有发送手机号，保持原有的手机号不变
                
                // 只有当性别不为空时才更新
                if (request.getUserInfo().getGender() != null) {
                    user.setGender(request.getUserInfo().getGender());
                }
                
                // 只有当省份不为空时才更新
                if (request.getUserInfo().getProvince() != null && !request.getUserInfo().getProvince().isEmpty()) {
                    user.setProvince(request.getUserInfo().getProvince());
                }
                
                // 只有当城市不为空时才更新
                if (request.getUserInfo().getCity() != null && !request.getUserInfo().getCity().isEmpty()) {
                    user.setCity(request.getUserInfo().getCity());
                }
                
                user.setUpdateTime(LocalDateTime.now());
                
                System.out.println("更新后用户信息: " + user);
                int updateResult = wechatUserMapper.updateById(user);
                System.out.println("更新结果: " + updateResult);
            }

            // 3. 重新查询用户信息（确保获取最新数据）
            user = wechatUserMapper.selectOne(wrapper);
            System.out.println("最终用户信息: " + user);
            System.out.println("最终用户手机号: " + user.getPhone());
            System.out.println("最终用户手机号是否为空: " + (user.getPhone() == null || user.getPhone().isEmpty()));

            // 4. 创建DTO并返回
            WechatUserDTO dto = new WechatUserDTO(user);
            System.out.println("返回给前端的DTO: " + dto);
            System.out.println("返回给前端的手机号: " + dto.getPhone());
            
            return R.ok(dto);
        } catch (WxErrorException e) {
            System.err.println("微信登录失败: " + e.getMessage());
            System.err.println("详细错误信息: " + e.toString());
            return R.failed("微信登录失败：" + e.getMessage());
        } catch (Exception e) {
            System.err.println("系统异常: " + e.getMessage());
            System.err.println("详细错误信息: " + e.toString());
            return R.failed("系统异常：" + e.getMessage());
        }
    }

    // 获取手机号接口
    @PostMapping("/get-phone")
    public R<String> getPhoneNumber(@RequestBody WxPhoneRequest request) {
        try {
            System.out.println("获取手机号请求: " + request);
            
            String phoneNumber;
            
            // 使用正确的微信SDK 4.4.0版本方法
            // getPhoneNoInfo需要3个参数：code, sessionKey, encryptedData
            // 对于新版本微信小程序，直接使用code即可
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(
                request.getCode(), 
                null,  // sessionKey - 可以为null
                null   // encryptedData - 可以为null
            );
            phoneNumber = phoneNoInfo.getPhoneNumber();
            
            System.out.println("解密后手机号: " + phoneNumber);
            
            // 如果用户已登录，更新手机号
            if (request.getOpenid() != null) {
                LambdaQueryWrapper<WechatUser> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(WechatUser::getOpenid, request.getOpenid());
                WechatUser user = wechatUserMapper.selectOne(wrapper);
                
                if (user != null) {
                    System.out.println("更新用户手机号，原手机号: " + user.getPhone());
                    user.setPhone(phoneNumber);
                    user.setUpdateTime(LocalDateTime.now());
                    int updateResult = wechatUserMapper.updateById(user);
                    System.out.println("手机号更新结果: " + updateResult);
                } else {
                    System.out.println("未找到用户，openid: " + request.getOpenid());
                }
            }
            
            return R.ok(phoneNumber);
        } catch (Exception e) {
            System.err.println("获取手机号失败: " + e.getMessage());
            System.err.println("详细错误信息: " + e.toString());
            return R.failed("获取手机号失败：" + e.getMessage());
        }
    }
}
